package com.stone.gateway.filter;

import cn.hutool.json.JSONUtil;
import com.stone.common.result.BaseResponse;
import com.stone.common.result.ErrorCode;
import com.stone.common.result.ResultUtils;
import com.stone.gateway.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Lazy;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;

@Slf4j
@Component
public class LoginGlobalFilter implements GlobalFilter {

    private AntPathMatcher pathMatcher = new AntPathMatcher();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("正在进行登录校验");
        // 放行登录和注册
        // TODO 改为读取配置的方式
        String path = exchange.getRequest().getURI().getPath();
        if(pathMatcher.match("/user/login" , path)||pathMatcher.match("user/register",path)){
            return chain.filter(exchange);
        }
        // 获取登录使用的JWT token
        String token = exchange.getRequest().getHeaders().getFirst("token");
        boolean isValid = JwtUtil.verifyToken(token);
        if(isValid){
            //放行
            return chain.filter(exchange);
        }else {
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.OK);
            response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
            // 构建返回的结果
            BaseResponse result = ResultUtils.error(ErrorCode.LOGIN_ERROR, "登录异常，提供的token不合法");
            DataBuffer buffer = response.bufferFactory().wrap(JSONUtil.toJsonStr(result).getBytes(StandardCharsets.UTF_8));
            return response.writeWith(Flux.just(buffer));
        }
    }
}